package idomains

import (
	"context"

	"gitee.com/djaf/my-certs/app/classes/domains"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/data/entity"
	"gitee.com/djaf/my-certs/app/web/dto"
)

// DomainServiceImpl ...
type DomainServiceImpl struct {

	//starter:component

	_as func(domains.Service) //starter:as("#")

	Dao domains.DAO //starter:inject("#")

}

func (inst *DomainServiceImpl) _impl() domains.Service {
	return inst
}

// Find ...
func (inst *DomainServiceImpl) Find(ctx context.Context, id dxo.DomainID) (*dto.Domain, error) {
	item1, err := inst.Dao.Find(nil, id)
	if err != nil {
		return nil, err
	}
	return domains.ConvertE2D(item1)
}

// List ...
func (inst *DomainServiceImpl) List(ctx context.Context) ([]*dto.Domain, error) {
	list, err := inst.Dao.List(nil)
	if err != nil {
		return nil, err
	}
	return domains.ConvertListE2D(list)
}

// Insert ...
func (inst *DomainServiceImpl) Insert(ctx context.Context, item1 *dto.Domain) (*dto.Domain, error) {

	item2, err := domains.ConvertD2E(item1)
	if err != nil {
		return nil, err
	}

	item3, err := inst.Dao.Insert(nil, item2)
	if err != nil {
		return nil, err
	}

	return domains.ConvertE2D(item3)
}

// Update ...
func (inst *DomainServiceImpl) Update(ctx context.Context, id dxo.DomainID, item1 *dto.Domain) (*dto.Domain, error) {

	item2, err := inst.Dao.Update(nil, id, func(ent *entity.Domain) {
		ent.Owner = item1.Owner
		ent.Group = item1.Group
		ent.Updater = 0 // todo: = current.user
	})

	if err != nil {
		return nil, err
	}

	return domains.ConvertE2D(item2)
}

// Remove ...
func (inst *DomainServiceImpl) Remove(ctx context.Context, id dxo.DomainID) error {
	return inst.Dao.Remove(nil, id)
}

// FindByName ...
func (inst *DomainServiceImpl) FindByName(ctx context.Context, name dxo.DomainName) (*dto.Domain, error) {
	ent, err := inst.Dao.FindByName(nil, name)
	if err != nil {
		return nil, err
	}
	return domains.ConvertE2D(ent)
}
